﻿$.L = {};
$.L.version = '0.0.1';
/*常量*/
(function () {
    $.extend($.L, {
        CONSTS: {
            // 分页相关
            pager: {
                //            TOTAL_MESSAGE: "总共{0}条记录,{1}/{2}页",
                TOTAL_MESSAGE: "共{0}条记录,当前{1}/{2}页",
                TOTAL_MESSAGE_ZREO: "共0条记录",
                PARAMETER_ERROR: "分页参数有错误",
                FIRST_PAGE: "首页",
                PRE_PAGE: "上一页",
                LAST_PAGE: "末页",
                NEXT_PAGE: "下一页",
                PAGEINDEX_OVERFLOW: "页索引超出范围"
            },
            message: {
                Not_Found: "请求地址错误",
                Internal_Server_Error: "服务器内部错误"
            }
        }
    })
})(jQuery);

/*常用方法*/
(function () {
    $.extend($.L, {
        /* @将指定字符串中的格式项替换为指定数组中相应对象的字符串表示形式 */
        stringFormat: function (str, array) {
            if (array.length == 0) return null;
            for (var i = 0; i < array.length; i++) {
                var re = new RegExp('\\{' + (i) + '\\}', 'gm');
                str = str.replace(re, array[i]);
            }
            return str;
        },
        defaultValue: function (value, defaultValue) {
            return value !== undefined && value !== '' ? value : defaultValue;
        },
        //超过长度省略显示
        ellipsis: function (value, len) {
            /// <summary>超过长度省略显示</summary>
            if (value && value.length > len) {
                return value.substr(0, len) + "...";
            }
            return value;
        },
        // 将字符串转换Date对象
        renderToDate: function (data) {
            if (data == null) return data;
            var da = eval('new ' + data.replace('/', '', 'g').replace('/', '', 'g'));
            return da;
        },
        // 对Date对象进行格式化
        dateFormat: function (time, format) {
            var o = {
                "M+": time.getMonth() + 1,  //month
                "d+": time.getDate(),     //day
                "h+": time.getHours(),    //hour
                "m+": time.getMinutes(),  //minute
                "s+": time.getSeconds(), //second
                "q+": Math.floor((time.getMonth() + 3) / 3),  //quarter
                "S": time.getMilliseconds() //millisecond
            }

            if (/(y+)/.test(format)) {
                format = format.replace(RegExp.$1, (time.getFullYear() + "").substr(4 - RegExp.$1.length));
            }

            for (var k in o) {
                if (new RegExp("(" + k + ")").test(format)) {
                    format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
                }
            }
            return format;
        },
        // 检测是否有重复元素
        hasRepeat: function (arr) {
            if (!arr || arr.length == 0 || arr.length == 1) return false;
            var newArr = [];
            for (var i = 0; i < arr.length; i++) {
                if (!$.inArray(arr[i], newArr)) {
                    newArr.push(arr[i]);
                }
            }
            return arr.length > newArr.length;
        },
        // 字符串左补充字符
        padLeft: function (value, length, sChar) {
            if (value.length >= length) return value;
            var _valueLength = value.length;
            for (var i = 0; i < length - _valueLength; i++) {
                value = sChar + value;
            }
            return value;
        },
        // 字符串右补充字符
        padRight: function (value, length, sChar) {
            if (value.length >= length) return value;
            var _valueLength = value.length;
            for (var i = 0; i < length - _valueLength; i++) {
                value = value + sChar;
            }
            return value;
        },
        // 添加收藏
        addFavorite: function (sURL, sTitle) {
            try {
                window.external.addFavorite(sURL, sTitle);
            }
            catch (e) {
                try {
                    window.sidebar.addPanel(sTitle, sURL, "");
                }
                catch (e) {
                    alert("加入收藏失败，请使用Ctrl+D进行添加");
                }
            }
        },
        // 设置主页
        setHome: function (c, a) {
            if (!$.isIE) {
                alert("您的浏览器不支持自动设置主页，请使用浏览器菜单手动设置。");
                return
            }
            var b = a;
            if (!b) {
                b = window.location.href
            }
            c.style.behavior = "url(#default#homepage)";
            c.setHomePage(b)
        },
        getCheckBoxData: function (name) {
            return $.map($("input[type='checkbox'][name='" + name + "']").filter(":checked"), function (a) { return $(a).val(); })
        },
        initCheckBox: function (itemName, allName) {
            if (!itemName) itemName = "chkItem";
            if (!allName) allName = "chkAll";

            $("input[type='checkbox'][name='" + allName + "']").on("click", function () {
                if ($(this).prop("checked")) {
                    $("input[type='checkbox'][name='" + itemName + "']").prop("checked", true);
                } else {
                    $("input[type='checkbox'][name='" + itemName + "']").prop("checked", false);
                }
            })

            $(document).on("click", "input[type='checkbox'][name='" + itemName + "']", function () {
                if ($("input[type='checkbox'][name='" + itemName + "']").not(":checked").length == 0) {
                    $("input[type='checkbox'][name='" + allName + "']").prop("checked", true);
                } else {
                    $("input[type='checkbox'][name='" + allName + "']").prop("checked", false);
                }
            })
        }
    })

})(jQuery);

(function () {

    $.fn.extend({
        enterKey: function (event) {
            $(this).keydown(function (e) {
                if (e.keyCode == $.CONSTS.keyCode.ENTER) {
                    event();
                }
            })
        }
    })

})(jQuery);

/*提示消息*/
(function () {
    $.extend($.L, {
        showModal: function (handle) {
            $("body").append('<div class="l_modal" id="l_modal"></div>');
            if (handle) {
                $("#l_modal").click(function () {
                    handle();
                })
            }
        },
        closeModal: function () {
            //$("#l_modal").fadeOut(300, function () {
            $("#l_modal").remove();
            //})
        }
    })
})(jQuery);

(function () {
    $.extend($.L, {
        loadingIcon: function (type, options) {
            this.loadingIconClose();

            if (!type) type = 1;

            var defaultOptions = {
                modal: true,
                container: $("body")
            }

            $.extend(defaultOptions, options);

            if (defaultOptions.modal == true) {
                this.showModal();
            }

            defaultOptions.container.append('<div class="l_loadingIcon l_loadingIcon_' + type + '" id="lgh_loading"></div>');

        },
        loadingIconClose: function () {
            this.closeModal();
            //$("#lgh_loading").fadeOut(300, function () {
            $("#lgh_loading").remove();
            //})
        }
    })
})(jQuery);

(function () {
    var _this = $.L;

    var _l_messageQTimeId = null;

    $.extend($.L, {
        messageQClose: function (handle) {
            this.closeModal();
            //$("#l_messageQ").fadeOut(300, function () {
            $("#l_messageQ").remove();
            if (handle) {
                handle();
            }
            //})
        },
        messageQ: function (type, content, handle) {
            if (_l_messageQTimeId) clearTimeout(_l_messageQTimeId);
            this.messageQClose();

            var html = _createHtml(type, content);

            this.showModal(function () {
                if (type != "Success" && type != "Loading") {
                    $.L.messageQClose(handle);
                }
            });

            _appendHtml($("body"), html);

            if (type == "Success") {

                _l_messageQTimeId = setTimeout(function () {

                    $.L.messageQClose(handle);

                }, 1500);

            }

            function _createHtml(_type, _content) {
                var _html = '<div id="l_messageQ" class="l_messageQ lgh_message' + _type + 'Q">'
                    + '<div class="l_messageQ_Icon"></div><div class="l_messageQ_Html">' + _content + '</div></div>'
                return _html;
            }

            function _appendHtml(container, _html) {
                container.append(_html);
                var _w = $("#l_messageQ").width();
                var _h = $("#l_messageQ").height();

                $("#l_messageQ").css({
                    'margin-left': '-' + _w / 2 + 'px',
                    'margin-top': '-' + _h / 2 + 'px'
                }).fadeIn();
            }


        },
        messageLoadingQ: function (content, handle) {

            this.messageQ("Loading", content, handle);

        },
        messageSuccessQ: function (content, handle) {

            this.messageQ("Success", content, handle);

        },
        messageWarningQ: function (content, handle) {

            this.messageQ("Warning", content, handle);

        },
        messagePromptQ: function (content, handle) {

            this.messageQ("Prompt", content, handle);

        },
        messageErrorQ: function (content, handle) {

            this.messageQ("Error", content, handle);
        }
    })
})(jQuery);

(function () {
    var _this = $.L;

    $.extend($.L, {
        messageTClose: function (handle) {
            this.closeModal();
            //$("#lgh_messageT").fadeOut(300, function () {
            $("#lgh_messageT").remove();
            if (handle) {
                handle();
            }
            //})
        },
        messageT: function (type, content, handle, cancleHandle) {
            this.messageTClose();

            var html = _createHtml(type, content);

            this.showModal();

            _appendHtml($("body"), html);

            function _createHtml(_type, _content) {
                var _html = '<div id="lgh_messageT" class="lgh_messageT lgh_message' + _type + 'T">'
                    + '<div class="lgh_messageT_Icon"></div><div class="lgh_messageT_Html">' + _content + '</div>'
                    + '<div class="lgh_messageT_Button">' + _createButton() + '</div>'
                    + '</div>'
                return _html;
            }

            function _createButton() {
                if (type == "Success") {
                    return "<a class='tbutton'>确定</a>";
                } else if (type == "Error") {
                    return "<a class='tbutton'>关闭</a>";
                } else if (type == "Warning") {
                    return "<a class='tbutton'>关闭</a>";
                } else if (type == "Confirm") {
                    return "<a a_type='cancle' class='tbutton'>取消</a><a class='tbutton'>确定</a> ";
                }
            }

            function _appendHtml(container, _html) {
                container.append(_html);

                _defineButtonClickEvent();

                var _w = $("#lgh_messageT").width();
                var _h = $("#lgh_messageT").height();
                _w += 36;
                _h += 36;


                $("#lgh_messageT").css({
                    'margin-left': '-' + _w / 2 + 'px',
                    'margin-top': '-' + _h / 2 + 'px'
                }).fadeIn();



            }

            function _defineButtonClickEvent() {
                $("#lgh_messageT").find("a.tbutton").click(function () {
                    var a_t = this;
                    $.L.messageTClose(function () {
                        if ($(a_t).attr("a_type") == "cancle") {
                            if (cancleHandle) cancleHandle();
                        } else {
                            if (handle) handle();
                        }
                    });
                })
            }


        },
        messageConfirmT: function (content, handle) {

            this.messageT("Confirm", content, handle);

        },
        messageSuccessT: function (content, handle) {

            this.messageT("Success", content, handle);

        },
        messageWarningT: function (content, handle) {

            this.messageT("Warning", content, handle);

        },
        messageErrorT: function (content, handle) {

            this.messageT("Error", content, handle);
        }
    })
})(jQuery);

(function () {
    $.fn.extend({
        L_loadingIcon: function (type, options) {
            if (!options) options = {};
            options.container = $(this);
            $.L.loadingIcon(type, options);
        }
    })
})(jQuery);

(function () {
    $.extend($.L, {
        dialog: function (param) {
            var obj = {};
            var defaultParam = {
                id: "bs_dialog_" + Math.ceil(Math.random() * 10000),
                url: "",
                html: null,
                isIframe: false,
                titleVisible: true,
                iframeId: "bs_dialog_iframe_" + Math.ceil(Math.random() * 10000),
                title: "无标题",
                width: document.documentElement.clientWidth * 0.8,
                height: document.documentElement.clientHeight * 0.8,
                buttons: null,
                close: function () { }
            }

            $.extend(defaultParam, param);

            _InitBSModal();
            _InitBSModalEvent();
            _InitBSModalButtons();
            if (defaultParam.html) {
                _InitBSModalContent();
            } else if (defaultParam.isIframe == true) {
                _InitBSModalContent();

            } else {
                setTimeout(_InitBSModalContent, 500);
            }
                //_InitBSModalContent();
            //_InitBSModalContent();

            function _InitBSModal() {
                // 向body添加BootStrap modal层元素
                $("body").append('<div class="modal fade" id="' + defaultParam.id + '" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">'
                              + '<div class="modal-dialog">'
                                + '<div class="modal-content">'
                                  + '<div class="modal-header"   style="cursor:move">'
                                    + '<button type="button" class="close" data-dismiss="modal"  title="关闭窗口"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>'
                                    + '<h4 class="modal-title"><span class="glyphicon glyphicon-list-alt" style="margin-right:6px;vertical-align:middle;margin-top:-5px;cursor:pointer;"  title="双击关闭窗口"></span>' + defaultParam.title + '</h4>'
                                  + '</div>'
                                  + '<div class="modal-body" style="overflow:auto;">'
                                  + '<div class="dialog_loading">努力加载中...</div>'
                                  + '</div>'
                                  + '<div class="modal-footer">'
                                  + '</div>'
                                + '</div>'
                              + '</div>'
                            + '</div>');
            }

            function _InitBSModalEvent() {

                if (defaultParam.titleVisible == false) {
                    $("#" + defaultParam.id + " .modal-header").remove();
                }

                $("#" + defaultParam.id + " .modal-dialog").css({
                    "width": defaultParam.width + "px"
                })

                if (defaultParam.height != "auto") {
                    $("#" + defaultParam.id + " .modal-body").css({
                        "height": defaultParam.height + "px"
                    })
                }

                $("#" + defaultParam.id + " .modal-header").find("span.glyphicon").dblclick(function () {
                    $('#' + defaultParam.id).modal("hide");
                })

                $('#' + defaultParam.id).modal({
                    backdrop: 'static'
                })

                $('#' + defaultParam.id).on('hidden.bs.modal', function (e) {
                    console.log("close");
                    defaultParam.close();
                    $("#" + defaultParam.id).remove();
                })

                $('#' + defaultParam.id).on('show.bs.modal', function (e) {
                    console.log("show");
                })


                if (defaultParam.titleVisible == true) {
                    $('#' + defaultParam.id).css({ "top": (document.documentElement.clientHeight - defaultParam.height - 70 - 60) / 2 - 30 + "px" })
                } else {
                    $('#' + defaultParam.id).css({ "top": (document.documentElement.clientHeight - 200) / 2 - 30 + "px" })
                }
            }

            function _InitBSModalButtons() {
                if (defaultParam.buttons) {
                    for (var a in defaultParam.buttons) {
                        var _btnHtml = "";
                        _btnHtml += '<button type="button" data-btnname="' + a + '" class="btn btn-' + defaultParam.buttons[a].type + '" '
                        if (defaultParam.buttons[a].click == "MODALMISS") {
                            _btnHtml += 'data-dismiss="modal"';
                        }
                        _btnHtml += '>' + defaultParam.buttons[a].text + '</button>';
                        $('#' + defaultParam.id).find(".modal-footer").append(_btnHtml);
                    }
                    $('#' + defaultParam.id).find(".modal-footer").find("button").click(function () {
                        var _name = $(this).attr("data-btnname");
                        if ($.isFunction(defaultParam.buttons[_name].click)) {
                            defaultParam.buttons[_name].click();
                        }
                    })
                }
            }

            function _InitBSModalContent() {
                if (defaultParam.html) {

                    $.L.loadingIconClose();
                    $("#" + defaultParam.id).find(".modal-body").html(defaultParam.html);

                } else if (defaultParam.isIframe == true) {

                    $.L.loadingIconClose();
                    $("#" + defaultParam.id).find(".modal-body").html("<iframe id='" + defaultParam.iframeId + "' src='" + defaultParam.url + "' style='width:100%;height:" + (defaultParam.height - 35) + "px;border:none;'></iframe>");

                } else {
                    //$.L.loadingIcon();
                    $.ajax({
                        url: defaultParam.url,
                        cache: false,
                        type: "GET",
                        dataType: "html",
                        error: function (XMLHttpRequest, errorInfo, exception) {
                            $.L.loadingIconClose();
                            $("#" + defaultParam.id).find(".modal-body").html(XMLHttpRequest);
                        },
                        success: function (response) {
                            $.L.loadingIconClose();
                            $("#" + defaultParam.id).find(".modal-body").html(response);
                        }
                    })
                }
            }

            obj.close = function () {
                $("#" + defaultParam.id).modal('hide');
            }

            return obj;
        },
        msgSuccess: function (message, okCallback,param) {
            var _html = '<div class="lgh_msg lgh_msgSuccess"><div class="lgh_msg_icon"></div><div class="lgh_msg_html">' + message + '</div></div>';
            if (!param) param = { text: "确认" };
            var _confirmDialog = $.L.dialog({
                html: _html,
                width: 500,
                height: "auto",
                titleVisible: false,
                buttons: {
                    "button_save": {
                        type: 'primary',
                        text: param.text,
                        click: function () {
                            _confirmDialog.close();
                            if (okCallback) okCallback();
                        }
                    }
                }
            });
        },
        msgWarning: function (message, okCallback) {
            var _html = '<div class="lgh_msg lgh_msgWarning"><div class="lgh_msg_icon"></div><div class="lgh_msg_html">' + message + '</div></div>';
            var _confirmDialog = $.L.dialog({
                html: _html,
                width: 500,
                height: "auto",
                titleVisible: false,
                buttons: {
                    "button_save": {
                        type: 'primary',
                        text: '确认',
                        click: function () {
                            _confirmDialog.close();
                            if (okCallback) okCallback();
                        }
                    }
                }
            });
        },
        msgError: function (message, okCallback) {
            var _html = '<div class="lgh_msg lgh_msgError"><div class="lgh_msg_icon"></div><div class="lgh_msg_html">' + message + '</div></div>';
            var _confirmDialog = $.L.dialog({
                html: _html,
                width: 500,
                height: "auto",
                titleVisible: false,
                buttons: {
                    "button_save": {
                        type: 'primary',
                        text: '确认',
                        click: function () {
                            _confirmDialog.close();
                            if (okCallback) okCallback();
                        }
                    }
                }
            });
        },
        msgConfirm: function (message, okCallback, cancleCallback) {
            var _html = '<div class="lgh_msg lgh_msgConfirm"><div class="lgh_msg_icon"></div><div class="lgh_msg_html">' + message + '</div></div>';
            var _confirmDialog = $.L.dialog({
                //url: ACTION_URL("ProgramAddOrEdit", "ProgramManager"),
                html: _html,
                width: 500,
                height: "auto",
                titleVisible: false,
                buttons: {
                    "button_save": {
                        type: 'primary',
                        text: '确认',
                        click: function () {
                            _confirmDialog.close();
                            if (okCallback) okCallback();
                        }
                    },
                    "button_cancel": {
                        type: 'default',
                        text: '取消',
                        click: function () {
                            _confirmDialog.close();
                            if (cancleCallback) cancleCallback();
                        }
                    }
                }
            });
        }
    })
})(jQuery);

/*分页显示*/
(function () {
    $.extend($.L, {
        createPageData: function (array, pageIndex, pageSize) {
            if (!array) return null;
            if (!pageIndex) pageIndex = 1;
            var result = {
                PageIndex: pageIndex,
                PageSize: pageSize,
                TotalItemCount: 0,
                PageData: null
            };
            if (!array) return null;
            result.TotalItemCount = array.length;
            result.PageData = $.grep(array, function (a, i) {
                return (i + 1) > ((pageIndex - 1) * pageSize) && (i + 1) <= (pageIndex * pageSize);
            })
            return result;
        }
    })
    $.fn.extend({
        formSubmit: function (pageIndex) {
            if ($(this).find("input[type='hidden'][name='pageIndex']").size() == 0) {
                $(this).append("<input type='hidden' id='pageIndex' name='pageIndex'/>");
            }
            if ($(this).find("input[type='hidden'][name='pageIndex']")) {
                if (pageIndex) {
                    $(this).find("input[type='hidden'][name='pageIndex']").val(pageIndex);
                } else {
                    $(this).find("input[type='hidden'][name='pageIndex']").val('');
                }
                $(this).submit();
            }
        },
        createPager: function (property) {
            var pageHtml = "";
            var pageUrl = "";

            // 是否需要前面显示...
            var preEtc = false;
            // 是否需要后面显示...
            var nextEtc = false;
            // 是否需要前面显示上一页
            var prePage = true;
            // 是否需要后面显示后一页
            var nextPage = true;

            var TOTAL_MESSAGE = "<span class='total'>" + $.L.CONSTS.pager.TOTAL_MESSAGE + "</span>";
            var TOTAL_MESSAGE_ZREO = "<span class='total'>" + $.L.CONSTS.pager.TOTAL_MESSAGE_ZREO + "</span>";
            var A_LINK_FORMAT = "<a href='{0}'>{1}</a>";
            var A_LINK_CURRENT_FORMAT = "<a href='JavaScript:;' class='sel'>{1}</a>";
            var A_LINK_DISABLED_FORMAT = "<a disabled='disabled'>{0}</a>";

            var PARAMETER_ERROR = $.L.CONSTS.pager.PARAMETER_ERROR;
            var FIRST_PAGE = $.L.CONSTS.pager.FIRST_PAGE;
            var PRE_PAGE = $.L.CONSTS.pager.PRE_PAGE;
            var LAST_PAGE = $.L.CONSTS.pager.LAST_PAGE;
            var NEXT_PAGE = $.L.CONSTS.pager.NEXT_PAGE;
            var PAGEINDEX_OVERFLOW = $.L.CONSTS.pager.PAGEINDEX_OVERFLOW;

            // 默认分页属性
            var PagerProperty = {
                pageIndex: 1,
                pageSize: 10,
                total: null,
                pageNum: 0,
                pageCount: 8,
                formId: null,
                needButton: false,
                linkClick: null,
                linkFun: null,
                numberVisible: true
            };

            $.extend(PagerProperty, property);

            $(this).html('');
            if ($(this).attr("numberVisible") == "false") {
                PagerProperty.numberVisible = false;
            }
            if ($(this).attr("pageCount")) {
                PagerProperty.pageCount = parseInt($(this).attr("pageCount"));
            }
            if (!property || (!property.total && property.total != 0)) {
                $.messageWarning(PARAMETER_ERROR);
                return;
            }

            // 总共的页数
            PagerProperty.pageNum = PagerProperty.total == 0 ? 0 : (Math.ceil(PagerProperty.total / PagerProperty.pageSize));

            //            PagerProperty.pageCount = PagerProperty.pageCount > PagerProperty.pageNum ? PagerProperty.pageNum : PagerProperty.pageCount;

            if (PagerProperty.pageNum == 0 || PagerProperty.pageCount == 0 || PagerProperty.pageNum == 1) {
                if ($(this).attr('container')) {
                    $("#" + $(this).attr('container')).hide();
                } else {
                    $(this).hide();
                }
                //$(this).html(TOTAL_MESSAGE_ZREO);
                return;
            } else {
                if ($(this).attr('container')) {
                    $("#" + $(this).attr('container')).show();
                } else {
                    $(this).show();
                }
            }

            $(this).addClass("lgh_pager");
            $(this).attr("PageIndex", PagerProperty.pageIndex);
            //            if ($(this).attr('showTotal')) {
            pageHtml = $.L.stringFormat($(this).attr("totalFormat") ? ("<span class='total'>" + $(this).attr("totalFormat") + "</span>") : TOTAL_MESSAGE, new Array(PagerProperty.total, PagerProperty.pageIndex, PagerProperty.pageNum));
            //            }

            if (PagerProperty.pageIndex != 1) {
                prePage = true;
            }
            if (PagerProperty.pageIndex != PagerProperty.pageNum) {
                nextPage = true;
            }

            var arr = createPageNumbers(PagerProperty.pageIndex, PagerProperty.pageNum, PagerProperty.pageCount);

            pageHtml += "<ul class='pager'>";

            if (PagerProperty.pageIndex == 1) {
                pageHtml += '<li class="disabled"><a href="JavaScript:;">上一页</a></li>'
            } else {
                pageHtml += '<li >' + $.L.stringFormat(A_LINK_FORMAT, createLinkHtml(PagerProperty.pageIndex - 1, PRE_PAGE)) + '</li>'
            }

            if (PagerProperty.pageIndex >= PagerProperty.pageNum) {
                pageHtml += '<li class="disabled"><a href="JavaScript:;">下一页</a></li>'
            } else {
                pageHtml += '<li >' + $.L.stringFormat(A_LINK_FORMAT, createLinkHtml(PagerProperty.pageIndex + 1, NEXT_PAGE)) + '</li>'
            }

            //if (!PagerProperty.numberVisible) {
            //    if (PagerProperty.pageIndex != 1) {
            //        pageHtml += "<li>" + $.L.stringFormat(A_LINK_FORMAT, createLinkHtml(1, FIRST_PAGE)) + "</li>";
            //    }
            //}

            //if (prePage == true && PagerProperty.pageIndex > 1) {
            //    pageHtml += "<li>" + $.L.stringFormat(A_LINK_FORMAT, createLinkHtml(PagerProperty.pageIndex - 1, PRE_PAGE)) + "</li>";
            //}
            //if (PagerProperty.numberVisible) {
            //    pageHtml += makeALinkHtml(PagerProperty.pageIndex, 1);

            //    if (preEtc) {
            //        pageHtml += "<li><span class='etc'>...</span></li>"
            //    }

            //    for (var i = 0; i < arr.length; i++) {
            //        pageHtml += makeALinkHtml(PagerProperty.pageIndex, arr[i]);
            //    }
            //    if (nextEtc) {
            //        pageHtml += "<li><span class='etc'>...</span></li>"
            //    }
            //    pageHtml += makeALinkHtml(PagerProperty.pageIndex, PagerProperty.pageNum);
            //}
            //if (nextPage == true && PagerProperty.pageIndex < PagerProperty.pageNum) {
            //    pageHtml += "<li>" + $.L.stringFormat(A_LINK_FORMAT, createLinkHtml(PagerProperty.pageIndex + 1, NEXT_PAGE)) + "</li>";
            //}
            //if (!PagerProperty.numberVisible) {
            //    if (PagerProperty.pageIndex != PagerProperty.pageNum) {
            //        pageHtml += "<li>" + $.L.stringFormat(A_LINK_FORMAT, createLinkHtml(PagerProperty.pageNum, LAST_PAGE)) + "</li>";
            //    }
            //}
            //if (this.needButton) {
            //    pageHtml += "<li><input type='text' style='width:25px;height:15px;line-height:15px;margin-bottom:3px;margin-left:5px;font-size:13px;' value='" + this.pageIndex + "'/><input type='button' value='跳转'/></li>"
            //}
            pageHtml += "</ul>"

            $(this).html(pageHtml);

            var _linkFun = PagerProperty.linkFun;
            var _pageNum = PagerProperty.pageNum;
            if ($(this).find("input[type='text']").length != 0) {
                $(this).find("input[type='text']").blur(function () {
                    if ($(this).val() == "") return;
                    var strP = /^[1-9]\d*$/;
                    if (!strP.test($(this).val())) {
                        alert(PAGEINDEX_OVERFLOW);
                        $(this).val('');
                        $(this).focus();
                    } else {
                        if (parseInt($(this).val()) > _pageNum) {
                            alert(PAGEINDEX_OVERFLOW);
                            $(this).val('');
                            $(this).focus();
                        }
                    }
                })
                $(this).find("input[type='button']").click(function () {
                    _linkFun(parseInt($(this).siblings("input[type='text']").val()));
                })
            }

            function makeALinkHtml(pageIndex, num) {
                if (num == pageIndex) {
                    return "<li>" + $.L.stringFormat(A_LINK_CURRENT_FORMAT, createLinkHtml(num, num)) + "</li>";
                } else {
                    return "<li>" + $.L.stringFormat(A_LINK_FORMAT, createLinkHtml(num, num)) + "</li>";
                }
            }

            function createPageNumbers(pageIndex, pageNum, pageCount) {
                var arr = new Array();
                var half = pageCount / 2;
                if (pageNum <= pageCount) {
                    for (var i = 2; i < pageNum; i++) {
                        arr.push(i);
                    }
                } else if (pageIndex <= half) {
                    nextEtc = true;
                    for (var i = 2; i < (3 + half) ; i++) {
                        arr.push(i);
                    }
                } else if (pageIndex >= (pageNum - half + 1)) {
                    preEtc = true;
                    for (var i = (pageNum - pageCount + 3) ; i < pageNum; i++) {
                        arr.push(i);
                    }
                } else {
                    preEtc = true;
                    nextEtc = true;
                    for (var i = (pageIndex - half + 2) ; i <= (pageIndex + half - 2) ; i++) {
                        arr.push(i);
                    }
                }

                return arr;
            }

            function createPageUrl(pageIndex) {
                if (PagerProperty.formId && typeof (PagerProperty.formId) == "string") {
                    return $.L.stringFormat("JavaScript:$(\"#{0}\").formSubmit({1})", new Array(PagerProperty.formId, pageIndex));
                } else if (PagerProperty.linkClick && typeof (PagerProperty.linkClick) == "string") {
                    return $.L.stringFormat("JavaScript:{0}({1})", new Array(PagerProperty.linkClick, pageIndex));
                } else if (PagerProperty.linkClick == null) {
                    return getLocationHref(pageIndex);
                }
            }

            function getLocationHref(pageIndex) {
                if (window.location.search == "")
                    return window.location.href + "?pageIndex=" + pageIndex;
                var _href = window.location.href.substring(0, window.location.href.indexOf("?"));

                if (window.location.search.indexOf("?pageIndex") == -1)
                    return _href + "?pageIndex=" + pageIndex + "&" + window.location.search.substring(1);

                if (window.location.search.indexOf("&") != -1) {
                    return _href + "?pageIndex=" + pageIndex + window.location.search.substring(window.location.search.indexOf("&"));
                } else {
                    return _href + "?pageIndex=" + pageIndex;
                }
            }

            function createLinkHtml(pageIndex, text) {
                var _arr = new Array();
                var _a_string = createPageUrl(pageIndex);
                _arr.push(_a_string);
                _arr.push(text);
                return _arr;
            }
        }
    })
})(jQuery);

/*Ajax相关*/
(function () {
    $.extend($.L, {
        ajaxHandle: function (options) {

            var defaultOptions = {
                url: "",
                type: "POST",
                data: {},
                loading: 1,
                loadingContainer: $("body"),
                error: function (response) { },
                success: function (response) { }
            };

            $.extend(defaultOptions, options);

            $.ajax({
                type: defaultOptions.type,
                url: defaultOptions.url,
                data: defaultOptions.data,
                beforeSend: function () {
                    if (defaultOptions.loading) {
                        $.L.loadingIcon(defaultOptions.loading, {
                            container: defaultOptions.loadingContainer
                        });
                    }
                },
                error: function (XMLHttpRequest, errorInfo, exception) {
                    $.L.loadingIconClose();
                    $.L.messageErrorT("【" + XMLHttpRequest.status + "】");
                },
                success: function (response, textStatus, jqXHR) {
                    $.L.loadingIconClose();
                    setTimeout(function () {
                        $.L.ajaxResultHandle(response, defaultOptions.success);
                    }, 300);
                }
            });
        },
        ajaxResultHandle: function (response, callback) {
            if (!response && response != 0) {
                return;
            }
            //if (response.e_type == 'modelstate') {
            //    for (var ele in response.e_content) {
            //        $.showElementModelStateMsg(ele, response.e_content[ele]);
            //    }
            //} else if (response.e_type == 'userexception') {
            //    $.messageErrorX(response.e_content);
            //} else if (response.e_type == 'exception') {
            //    $.messageErrorX($.CONSTS.message.Internal_Server_Error);
            //} else if (response.e_type == 'authorize') {
            //    location.reload();
            //} else {
            if (response.e_type) {
                if (response.e_type == "modelstate") {
                    for (var ele in response.e_content) {
                        $.L.showElementModelStateMsg(ele, response.e_content[ele]);
                    }
                } else if (response.e_type == "userexception") {
                    $.L.messageErrorT(response.e_content);
                } else if (response.e_type == "exception") {
                    $.L.messageErrorT(response.e_content);
                }
            } else if (callback) {
                callback(response);
            }
            //}
        },
        showElementModelStateMsg: function (ele, msg) {
            if (typeof (ele) == "string") {
                var obj = $("[name='" + ele + "']");
                var _span = $("span[data-valmsg-for='" + ele + "']");
                obj.addClass("input-validation-error");
                _span.removeClass("field-validation-valid").addClass("field-validation-error");
                _span.html('<span class="" for="' + ele + '" generated="true">' + msg + '</span>');

                obj.one("focus", function () {
                    obj.removeClass("input-validation-error");
                    _span.removeClass("field-validation-error").addClass("field-validation-valid");
                    _span.html('');
                })
            } else {
                var obj = ele;
                var _span = $("span[data-valmsg-for='" + ele.attr("name") + "']");
                obj.addClass("input-validation-error");
                _span.removeClass("field-validation-valid").addClass("field-validation-error");
                _span.html('<span class="" for="' + ele.attr("name") + '" generated="true">' + msg + '</span>');

                obj.one("focus", function () {
                    obj.removeClass("input-validation-error");
                    _span.removeClass("field-validation-error").addClass("field-validation-valid");
                    _span.html('');
                })
            }
        },
        removeElementModelStateMsg: function (ele) {
            if (typeof (ele) == "string") {
                var obj = $("[name='" + ele + "']");
                var _span = $("span[data-valmsg-for='" + ele + "']");
                obj.removeClass("input-validation-error");
                _span.removeClass("field-validation-error").addClass("field-validation-valid");
                _span.html('');
            } else {
                var obj = ele;
                var _span = $("span[data-valmsg-for='" + ele.attr("name") + "']");
                obj.removeClass("input-validation-error");
                _span.removeClass("field-validation-error").addClass("field-validation-valid");
                _span.html('');
            }
        }
    })
})(jQuery);

/*数据绑定*/
(function () {
    $.fn.extend({
        L_bindingDataProperty: function (data, baseData) {
            var property = GetL_bindingDataProperty($(this));
            //ASDASD
            if (!property) return;

            for (var _pro in property) {
                if (_pro.indexOf("Format") != -1
                || _pro.indexOf("Handle") != -1
                || _pro.indexOf("Length") != -1
                || _pro.indexOf("Data") != -1
                || _pro.indexOf("lazyLoad") != -1)
                    continue;

                if (_pro == 'text') {
                    var _re = GetDataPropertyInfo(property.text,
                        property.textHandle,
                        property.textFormat,
                        $(this),
                        data);
                    if (_re != null && _re != undefined) {
                        if (property.textData && property.textData[_re]) {
                            $(this).text(property.textData[_re]);
                        } else if (property.textLength) {
                            $(this).text($.ellipsis(_re, property.textLength));
                            $(this).attr("title", _re);
                        } else {
                            $(this).text(_re);
                        }
                    }
                } else if (_pro == 'html') {
                    var _html = GetDataPropertyInfo(property.html,
                            property.htmlHandle,
                            property.htmlFormat,
                            $(this),
                            data);
                    if (_html != null && _html != undefined) {
                        if (property.htmlData && property.htmlData[_html]) {
                            $(this).html(property.htmlData[_html]);
                        } else {
                            $(this).html(_html);
                        }
                    }
                } else if (_pro == 'value') {
                    var _value = GetDataPropertyInfo(property.value,
                        property.valueHandle,
                        property.valueFormat,
                        $(this),
                        data);
                    if (_value != null && _value != undefined) {
                        if (property.valueData && property.valueData[_value]) {
                            $(this).val(property.valueData[_value]);
                        } else {
                            $(this).val(_value);
                        }
                    }
                } else if (_pro == 'list') {
                    var BindingTempleteID = "BindingTemplete_" + $(this).attr("list_id");
                    if (!window[BindingTempleteID]) {
                        window[BindingTempleteID] = $(this).html();
                    }

                    $(this).L_bindingDataList(data[property.list], { bindingformat: window[BindingTempleteID], baseData: data });
                } else {
                    var _attr = GetDataPropertyInfo(property[_pro],
                            property[_pro + "Handle"],
                            property[_pro + "Format"],
                            $(this),
                            data);
                    if (_attr != null && _attr != undefined) {
                        if (property[_pro + "Data"] && property[_pro + "Data"][_attr]) {
                            $(this).attr(_pro, property[_pro + "Data"][_attr]);
                        } else {
                            $(this).attr(_pro, _attr)
                        }
                    }
                }
            }

            function GetDataPropertyInfo(text, handle, format, obj, data, baseData) {
                if (handle) {
                    if ($.inArray(handle, $.dataBinder.options.typename) != -1) {
                        return $.dataBinder.options.rule[handle](GetJsonDataValue(data, text));
                    } else {
                        if (handle.indexOf && handle.indexOf("datetime=") != -1) {
                            var arr = handle.split('=');
                            return $.dataBinder.options.rule.datetime(GetJsonDataValue(data, text), arr[1]);
                        }
                        if (handle.indexOf && handle.indexOf("datetimeGMT=") != -1) {
                            var arr = handle.split('=');
                            return $.dataBinder.options.rule.datetimeGMT(GetJsonDataValue(data, text), arr[1]);
                        }
                        return handle(GetJsonDataValue(data, text, true), data, obj);
                    }
                } else {
                    if (format) {
                        return GetTextFormatResult(format, text, data);
                    } else {
                        return GetJsonDataValue(data, text);
                    }
                }
            }

            function GetL_bindingDataProperty(obj) {
                if (!obj || !obj.attr("binding")) {
                    return null;
                } else {
                    var _bindingStr = obj.attr("binding");
                    var returnObj;
                    try {
                        returnObj = eval("(" + _bindingStr + ")");
                    } catch (e) {
                        alert("GetL_bindingDataProperty" + e);
                    }
                    if (returnObj.source) {
                        try {
                            returnObj = eval("(" + returnObj.source + ")");
                        } catch (e) {
                            alert("GetL_bindingDataProperty" + e);
                        }
                    }
                    return returnObj;
                }
            }

            function GetTextFormatResult(format, dataProperty, data) {
                var _property = dataProperty.split(',');
                return $.L.stringFormat(format, $.map(_property, function (n) { return GetJsonDataValue(data, n); }));
            }

            function GetJsonDataValue(a, b, needZero) {
                if (b == undefined || b == null || b == '') return a;
                if (b.indexOf(".") == -1) {
                    if (a[b] === 0 && !needZero) return '0';
                    if (a[b] == undefined || a[b] == null) return '';
                    return a[b];
                } else {
                    var _arr = b.split('.');
                    var _value = a;

                    var _startIndex = 0;

                    if (_arr[0] == "base" && baseData) {
                        _value = baseData;
                        _startIndex = 1;
                    }

                    for (var i = _startIndex; i < _arr.length; i++) {
                        if (_value != null && _value != undefined) {
                            _value = _value[_arr[i]];
                        }
                    }
                    return _value;
                }
            }
        },
        L_bindingData: function (data, baseData) {
            $(this).find("[binding]").add(this).each(function () {
                $(this).L_bindingDataProperty(data, baseData);
            })
            return $(this);
        },
        L_bindingDataList: function (list, para) {
            if (!para) para = {};

            var bindingformat = para.bindingformat;
            var baseData = para.baseData;

            if ($(this).size() == 0) return;
            if ($(this).length == undefined) return;
            if (!bindingformat && !$(this).data("BindingFormat")) {
                $(this).data("BindingFormat", $(this).html());
                $(this).html('');
                $(this).hide();
            }

            if (!bindingformat && !$(this).data("BindingFormat")) {
                return $(this);
            }

            if (!bindingformat) {
                bindingformat = $(this).data("BindingFormat");
            }

            var property = eval("(" + $(this).attr("binding") + ")");

            var data = list;
            if (property && property.pageId) {
                data = list.PageData;
            }
            if (property && property.emptyHtml && (!data || data.length == 0)) {
                if (property.emptyHtml.indexOf('#') == 0) {
                    property.emptyHtml = $(property.emptyHtml).html();
                }
                $(this).html(property.emptyHtml);
                $(this).show();

                if (property.pageId) {
                    $("#" + property.pageId).html('');
                }

                return $(this);
            }
            if (!data) return $(this);
            $(this).html('');
            for (var i = 0; i < data.length; i++) {
                var formatObj = $(bindingformat);
                data[i].Binding_Index = i + 1;
                formatObj.L_bindingData(data[i], baseData);
                $(this).append(formatObj);
                if (para.itemHandle) {
                    para.itemHandle(i, formatObj, data[i]);
                }
            }
            $(this).show();

            if (property && property.pageId) {
                $("#" + property.pageId).createPager({
                    pageIndex: list.PageIndex,
                    pageSize: list.PageSize,
                    total: list.TotalItemCount,
                    formId: property.formId ? property.formId : null,
                    linkClick: property.pageCallback
                });
            }
            return $(this);
        }
    })
    $.dataBinder = {
        options: {
            typename: new Array("datetime", "filesize", "datetimeGMT", "datetime_Date", "datetimeGMT_Date"),
            rule: {
                datetime: dataBinder_Datetime,
                filesize: dataBinder_FileSize,
                datetimeGMT: dataBinder_DateTimeGMT,
                datetime_Date: dataBinder_DateTime_Date,
                datetimeGMT_Date: dataBinder_DateTimeGMT_Date
            }
        },
        addMethod: function (name, handle) {
            $.dataBinder.options.typename.push(name);
            $.dataBinder.options.rule[name] = handle;
        }
    }
    function dataBinder_Datetime(value, format) {
        if (!value) return "";
        if (!format) { format = "yyyy-MM-dd hh:mm:ss"; }
        return $.L.dateFormat($.L.renderToDate(value), format)
    }
    function dataBinder_DateTime_Date(value) {
        if (!value) return "";
        return $.L.dateFormat($.L.renderToDate(value), "yyyy-MM-dd")
    }
    function dataBinder_FileSize(value) {
        if (!value) return "";
        return $.fileSize(value);
    }
    function dataBinder_DateTimeGMT(value, format) {
        if (!value) return "";
        if (!format) { format = "yyyy-MM-dd hh:mm:ss"; }
        value = value.replace("GMT+08:00", "GMT+08");
        value = value.replace("GMT+0800", "GMT+08");
        value = value.replace("+0800", "GMT+08");
        var _date = new Date(value);
        return $.L.dateFormat(_date, format)
    }
    function dataBinder_DateTimeGMT_Date(value) {
        if (!value) return "";
        value = value.replace("GMT+08:00", "GMT+08");
        var _date = new Date(value);
        return $.L.dateFormat(_date, "yyyy-MM-dd")
    }
})(jQuery);

(function () {
    $.extend({
        w_socket: function (param) {
            var defaultParam = {
                url: "",
                onstart: function () { },
                onopen: function () { },
                onclose: function () { },
                onerror: function () { },
                onmessage: function () { },
                onexception: function (ex) { },
                onnotsupport: function () { }
            }

            $.extend(defaultParam, param);
            var obj = {};
            var _socket;

            try {
                var support = "MozWebSocket" in window ? 'MozWebSocket' : ("WebSocket" in window ? 'WebSocket' : null);

                if (support == null) {
                    defaultParam.onnotsupport();
                    return null;
                }

                _socket = new window[support](defaultParam.url);

                _socket.onopen = function () {
                    defaultParam.onopen();
                }

                _socket.onclose = function (evt) {
                    defaultParam.onclose();
                }

                _socket.onerror = function (evt) {
                    defaultParam.onerror();
                }

                _socket.onmessage = function (evt) {
                    defaultParam.onmessage(eval("(" + evt.data + ")"), evt.data);
                }

            } catch (e) {
                defaultParam.onexception(e);
                return null;
            }

            obj.send = function (jsonData) {
                if (typeof (jsonData) == 'string') {
                    _socket.send(jsonData);
                } else {
                    _socket.send($.jsonString(jsonData))
                }
            }

            obj.socket = _socket;
            return obj;
        }
    })
})(jQuery);

// jquery.sy.cookie.js
(function ($) {
    $.extend({
        cookie: function (name, value, options) {
            /// <summary>读取或设置Cookie</summary>
            /// <param></param>
            if (typeof value != 'undefined') { // name and value given, set cookie
                options = options || {}; { }
                if (value === null) {
                    value = '';
                    options.expires = -1;
                }
                var expires = '';
                if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                    var date;
                    if (typeof options.expires == 'number') {
                        date = new Date();
                        date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                    } else {
                        date = options.expires;
                    }
                    expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
                }
                // CAUTION: Needed to parenthesize options.path and options.domain
                // in the following expressions, otherwise they evaluate to undefined
                // in the packed version for some reason...
                var path = options.path ? '; path=' + (options.path) : '';
                var domain = options.domain ? '; domain=' + (options.domain) : '';
                var secure = options.secure ? '; secure' : '';
                document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
            } else { // only name given, get cookie
                var cookieValue = null;
                if (document.cookie && document.cookie != '') {
                    var cookies = document.cookie.split(';');
                    for (var i = 0; i < cookies.length; i++) {
                        var cookie = jQuery.trim(cookies[i]);
                        // Does this cookie string begin with the name we want?
                        if (cookie.substring(0, name.length + 1) == (name + '=')) {
                            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                            break;
                        }
                    }
                }
                return cookieValue;
            }
        },
        setCookie: function (name, value, options) {
            /// <summary>设置Cookie</summary>
            options = options || {};
            if (value === null) {
                value = '';
                options.expires = -1;
            }
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
            }
            // CAUTION: Needed to parenthesize options.path and options.domain
            // in the following expressions, otherwise they evaluate to undefined
            // in the packed version for some reason...
            var path = options.path ? '; path=' + (options.path) : '';
            var domain = options.domain ? '; domain=' + (options.domain) : '';
            var secure = options.secure ? '; secure' : '';
            document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
        },
        getCookie: function (name) {
            /// <summary>读取Cookie</summary> 
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        },
        deleteCookie: function (name) {
            /// <summary>删除Cookie</summary>
            var exp = new Date();
            exp.setTime(exp.getTime() - 1);
            var cval = $.getCookie(name);
            if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
        }
    })
})(jQuery);